﻿using System;
using System.Collections;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using DICOMViewer.Utility;
using Main3DDemo;
using Leadtools;
using Leadtools.Demos;
using Leadtools.DicomDemos;
using Leadtools.Medical3D;


// ReSharper disable All

namespace DICOMViewer
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main(string[] args)
        {
            //全局异常捕捉
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.ApplicationExit += Application_ApplicationExit;
            //            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            Process instance = RunningInstance();
            if (instance == null)
            {
                //MessageBox.Show("", "没有");
            }
            else
            {
                Console.WriteLine("enter hanle running instance!");
                HandleRunningInstance(instance);
                IntPtr hwndRecvWindow = instance.MainWindowHandle;

                ApplicationArgsUtility.SendArgsWinMessage(args, hwndRecvWindow);
                Process current = Process.GetCurrentProcess();
                current.Kill();
            }

            startApplication(args);
        }

        private static void Application_ApplicationExit(object sender, EventArgs e)
        {
            Utils.EngineShutdown();
            Utils.DicomNetShutdown();
        }

        private static void startApplication(string[] args)
        {
//            Assembly.Load(DICOMViewer.Properties.Resources.Leadtools);

            //设置License
            if (!Support.SetLicense())
                return;
            //leadtools验证liccense
            if (RasterSupport.IsLocked(RasterSupportType.DicomCommunication))
            {
                Console.WriteLine("License error!");
                MessageBox.Show(
                    String.Format("{0} Support is locked!", RasterSupportType.DicomCommunication.ToString()),
                    "Warning");
                return;
            }

            //对Uac进行判断，如果需要提升权限进行运行，已通过manifest设置requireAdministrator绕过
            if (DemosGlobal.MustRestartElevated())
            {
                Console.WriteLine("Try Restart Elevated !");
                DemosGlobal.TryRestartElevated(args);
                return;
            }
            //启动leadtools引擎，DicomEngine.Startup();
            Utils.EngineStartup();
            //DicomNet.Startup();
            Utils.DicomNetStartup();

            try
            {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();
            Application.DoEvents();
            if (!Medical3DEngine.HardwareCompatible)
            {
                MessageBox.Show("Hardware does not meet the required specifications required by the 3D engine.",
                    "Compatibility Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CheckUtilityDialog check = new CheckUtilityDialog(null);
                check.ShowDialog();
            }
            IncoolDicomViewerBase.IncoolDicomBaseClass.G_xDataSetConfigInterface =
                new IncoolDicomViewerBase.xDataSetConfigOnline();
            IncoolDicomViewerBase.IncoolDicomBaseClass.G_xDataSetConfigInterface.RequestURL =
                ConfigurationManager.AppSettings.Get("WeiXinInterFaceUrl");
            IncoolDicomViewerBase.IncoolDicomBaseClass.G_BLL_Object = new Hashtable();
             //按照命令行参数执行启动操作
            ApplicationArgsUtility.Excute(args);
            }catch (Exception ex)
            {
                Console.WriteLine(ex.Message+ ex.StackTrace+ex.Source);
            }
            finally
            {
                Utils.EngineShutdown();
                Utils.DicomNetShutdown();
            }
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            string errorMsg = "全局异常:" +"Message:{"+ e.Exception.Message + "}StackTree:{" + e.Exception.StackTrace + "}Source:{" + e.Exception.Source+"}innerexception:{"+e.Exception.InnerException?.Message??" null "+"||"+e.Exception.InnerException?.Source??" null "+"}";
            //处理全局异常
            MessageBox.Show(errorMsg);
            Logger.Log(DateTime.Now.ToString() + errorMsg);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            string errorMsg = "全局异常:" + "Message:{" + ex.Message + "}StackTree:{" + ex.StackTrace + "}Source:{" + ex.Source + "}innerexception:{" + ex.InnerException?.Message??" null " + "||" + ex.InnerException?.Source??" null " + "}";

            //处理全局异常
            MessageBox.Show(errorMsg);
            Logger.Log(DateTime.Now.ToString() + errorMsg);
        }

        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }

        private const int SW_MAXIMIZE = 3;
        private const int SW_RESTORE = 9;

        private static void HandleRunningInstance(Process instance)
        {
            WinMessageUtility.ShowWindowAsync(instance.MainWindowHandle, SW_MAXIMIZE); // SW_MAXIMIZE);//显示
            WinMessageUtility.SetForegroundWindow(instance.MainWindowHandle); //当到最前端
        }

        private static Process RuningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess();
            Process[] Processes = Process.GetProcessesByName(currentProcess.ProcessName);
            foreach (Process process in Processes)
            {
                if (process.Id != currentProcess.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
                        currentProcess.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
    }
}